package br.com.dallas.processamento;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import br.com.dallas.util.servlet.AbstractServlet;
import br.com.dallas.vendas.controller.VendaController;
import br.com.dallas.vendas.javabean.VendaBean;


public class SevletProcessaRequisicao extends AbstractServlet implements Serializable
{
	private static final long serialVersionUID = Long.MAX_VALUE;

	private static final int REQUISICAO_IMPRIMIR = 1;
	
	private static final String RELATORIO_LISTAGEM_VENDA = "/WEB-INF/relatorio/RelatorioVendas.jrxml";
	private static final String RELATORIO_GERAL_TRANSPORTADORA = "/WEB-INF/relatorio/RelatorioGeralTrasportadoras.jrxml";
	
	@Override
	protected void requisicao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		switch (getRequisicao(request))
		{	
			case REQUISICAO_IMPRIMIR:
			{
				imprimirRelatorio(request, response);
				break;
			}
			default:
			{
				break;
			}	
		}
	}
	
	@SuppressWarnings("unchecked")
	private void imprimirRelatorio(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{	
		RequestDispatcher requestDispatcher = null;
		ServletOutputStream outputStream = null;
		VendaBean vendaBean = null;
		HttpSession session = null;
		VendaController vendaController = null;
		List<VendaBean> listaVendasCorreta = null;
		List<VendaBean> listaTransportadora = null;
		try
		{	
			session = request.getSession();
			
			if (session.getAttribute("vendaBean") != null)
			{
				vendaBean = (VendaBean)session.getAttribute("vendaBean");
				listaVendasCorreta = getlistarSomenteVendasMarcadas(vendaBean.getListaClientePorTrasnportadora());
				
				if (listaVendasCorreta.size() > 0)
				{
					processaRelatorio(request, response, outputStream, listaVendasCorreta, RELATORIO_LISTAGEM_VENDA);
					vendaController = new VendaController();
					vendaController.inserirDocumentoImpressoWeb(listaVendasCorreta);
				}
				else
				{
					requestDispatcher = request.getRequestDispatcher("/view/dispatcher/ListaMensagem.jsf");
					requestDispatcher.forward(request, response);
				}
			}
			
			if (session.getAttribute("lista") != null)
			{
				listaTransportadora = (List<VendaBean>)session.getAttribute("lista");
				
				if (listaTransportadora.size() > 0)
				{
					processaRelatorio(request, response, outputStream, listaTransportadora, RELATORIO_GERAL_TRANSPORTADORA);
				}
				else
				{
					requestDispatcher = request.getRequestDispatcher("/view/dispatcher/ListaMensagem.jsf");
					requestDispatcher.forward(request, response);
				}
				
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			request.setAttribute("mensagemErro", e.getMessage());
			requestDispatcher = request.getRequestDispatcher("/view/dispatcher/PaginaErro.jsf");
			requestDispatcher.forward(request, response);
		}
		finally
		{
			if (session.getAttribute("vendaBean") != null)
				session.removeAttribute("vendaBean");
			
			if (session.getAttribute("lista") != null)
				session.removeAttribute("lista");
			
			if (vendaController != null)
			{
				vendaController.close();
				vendaController = null;
			}
		}
	}
	
	
	private List<VendaBean> getlistarSomenteVendasMarcadas(List<VendaBean> listaOrganizar)
	{
		List<VendaBean> listaOrganizada = new ArrayList<VendaBean>();
		for (int i = 0; i < listaOrganizar.size(); i++)
		{
			if (((VendaBean)listaOrganizar.get(i)).isImprimir())
				listaOrganizada.add(listaOrganizar.get(i));
		}
		
		if (listaOrganizada.size() == 0)
		{
			listaOrganizada.clear();
			listaOrganizada.addAll(listaOrganizar);
		}
		return listaOrganizada;
	}
	
	@SuppressWarnings("deprecation")
	private static void processaRelatorio(HttpServletRequest request, HttpServletResponse response, ServletOutputStream outputStream, List<VendaBean> listaVendas, String pathRelatorio)
	{
		JasperReport jasperReport = null;
		JasperPrint jasperPrint = null;
		byte[] bytes = null;
		try
		{
			if (listaVendas != null && listaVendas.size() > 0)
			{
				//jasperReport = JasperCompileManager.compileReport(request.getServletContext().getRealPath(pathRelatorio));
				jasperReport = JasperCompileManager.compileReport(request.getRealPath(pathRelatorio));
				bytes = JasperRunManager.runReportToPdf(jasperReport, null, new JRBeanCollectionDataSource(listaVendas));
				if (bytes != null && bytes.length > 0)
				{
					response.setContentType("application/pdf");
					response.setContentLength(bytes.length);
					outputStream = response.getOutputStream();
					outputStream.write(bytes, 0, bytes.length);
					if (outputStream != null)
					{
						outputStream.flush();
						outputStream.close();
					}
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (jasperPrint != null)
				jasperPrint = null;
			
			if (jasperReport != null)
				jasperReport = null;
		}
	}
}
